package com.bestcem.xm.award.mq;//package com.bestcem.xm.award.util.mq;
//
//import com.bestcem.xm.award.dao.AwardMqSendLogDao;
//import com.fasterxml.jackson.core.JsonProcessingException;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.amqp.core.Message;
//import org.springframework.amqp.core.MessageDeliveryMode;
//import org.springframework.amqp.core.MessageProperties;
//import org.springframework.amqp.rabbit.core.RabbitTemplate;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import javax.annotation.Resource;
//import java.util.UUID;
//
///**
// * mq消息发送工具类
// *
// * @author sh.pei <sh.pei@idiaoyan.com>
// * @version v1.0
// * @date 2021/8/1 16:29
// */
//@Slf4j
//@Service
//public class RabbitMqMessageSender {
//
//    @Resource
//    private AwardMqSendLogDao awardMqSendLogDao;
////
////    @Autowired
////    private RabbitTemplate rabbitTemplate;
//
//    /**
//     * 发送消息, 默认使用msg首字母小写的类名来作为消息体里的key
//     *
//     * @param exchange
//     * @param routingKey
//     * @param topic
//     * @param msg
//     */
////    public void sendMsg(String exchange, String routingKey, String topic, Object msg) throws JsonProcessingException {
////        Message dto = buildMsg(topic, msg);
////        rabbitTemplate.send(exchange, routingKey, dto);
////    }
//
////    /**
////     * 发送延迟消息, 默认使用msg首字母小写的类名来作为消息体里的key
////     *
////     * @param exchange
////     * @param routingKey
////     * @param topic
////     * @param msg
////     * @param delayTime  毫秒
////     * @throws JsonProcessingException
////     */
////    public void sendDelayMsg(String exchange, String routingKey, String topic, Object msg, Integer delayTime) throws JsonProcessingException {
////        Date delayDate = DateUtil.offset(new Date(), DateField.MILLISECOND, delayTime);
////        sendDelayMsg(exchange, routingKey, topic, msg, delayDate);
////    }
//
//    /**
//     * 发送延迟消息, 默认使用msg首字母小写的类名来作为消息体里的key
//     *
//     * @param exchange
//     * @param routingKey
//     * @param topic
//     * @param msg
//     * @param delayDate  消息要延迟消费的时间 UTC时区
//     * @throws JsonProcessingException
//     */
////    public void sendDelayMsg(String exchange, String routingKey, String topic, Object msg, Date delayDate) throws JsonProcessingException {
////        Message dto = buildMsg(topic, msg);
////        AwardMqSendLogDO awardMqSendLog = new AwardMqSendLogDO();
////        awardMqSendLog.setId(new ObjectId().toHexString());
////        awardMqSendLog.setExchangeName(exchange);
////        awardMqSendLog.setRoutingKey(routingKey);
////        awardMqSendLog.setTopic(topic);
////        awardMqSendLog.setContent(JSON.toJSONString(msg));
////        awardMqSendLog.setDelay(Boolean.TRUE);
////        awardMqSendLog.setDelayTime(delayDate);
////        awardMqSendLog.setSendMsg(Base64.getEncoder().encodeToString(dto.getBody()));
////        // 1天以内
////        if (delayDate.compareTo(DateUtil.offset(new Date(), DateField.DAY_OF_MONTH, 1)) <= 0) {
////            long delayTime = Math.max(delayDate.getTime() - System.currentTimeMillis(), 1L);
////            dto.getMessageProperties().getHeaders().put("x-delay", delayTime);
////            dto.getMessageProperties().getHeaders().put(AWARD_MQ_HEADER, awardMqSendLog.getId());
////            rabbitTemplate.send(exchange, routingKey, dto);
////            // 保存发送状态
////            awardMqSendLog.setStatus(MqSendStatusEnum.SEND_SUCCESS.getIndex());
////            awardMqSendLogDao.insert(awardMqSendLog);
////        } else {
////            // 保存发送状态
////            awardMqSendLog.setStatus(MqSendStatusEnum.TO_SEND.getIndex());
////            awardMqSendLogDao.insert(awardMqSendLog);
////        }
////
////    }
//
//    /**
//     * 定时任务,获取库里未来一天内的未发送的消息,并发送
//     */
////    public void mqSendJob() {
////        List<AwardMqSendLogDO> sendLogList = awardMqSendLogDao.listAwardMqSendLogs(MqSendStatusEnum.TO_SEND.getIndex(),
////                Boolean.TRUE, null, cn.hutool.core.date.DateUtil.offset(new Date(), DateField.DAY_OF_MONTH, 1));
////        if (!CollectionUtils.isEmpty(sendLogList)) {
////            for (AwardMqSendLogDO awardMqSendLog : sendLogList) {
////                try {
////                    Message dto = buildMsg(Base64.getDecoder().decode(awardMqSendLog.getSendMsg()));
////                    Date delayDate = awardMqSendLog.getDelayTime();
////                    long delayTime = Math.max(delayDate.getTime() - System.currentTimeMillis(), 1L);
////                    dto.getMessageProperties().getHeaders().put("x-delay", delayTime);
////                    dto.getMessageProperties().getHeaders().put(AWARD_MQ_HEADER, awardMqSendLog.getId());
////                    rabbitTemplate.send(awardMqSendLog.getExchangeName(), awardMqSendLog.getRoutingKey(), dto);
////                    Integer updateCount = awardMqSendLogDao.updateStatusById(awardMqSendLog.getId(), MqSendStatusEnum.SEND_SUCCESS.getIndex());
////                    if (updateCount != Constants.ONE) {
////                        log.error("[award] mqSendJob 修改消息状态失败 id:{}", awardMqSendLog.getId());
////                    }
////                    if (log.isInfoEnabled()) {
////                        log.info("[award] 发送延迟mq消息成功{}", awardMqSendLog);
////                    }
////                } catch (Exception e) {
////                    log.error("[award] 发送延迟mq消息失败", e);
////                    Integer updateCount = awardMqSendLogDao.updateStatusById(awardMqSendLog.getId(), MqSendStatusEnum.SEND_FAIL.getIndex());
////                    if (updateCount != Constants.ONE) {
////                        log.error("[award] mqSendJob 修改消息状态失败 id:{}", awardMqSendLog.getId());
////                    }
////                }
////            }
////        } else {
////            if (log.isInfoEnabled()) {
////                log.info("[award] 没有待发送的消息");
////            }
////        }
////    }
//
//    /**
//     * 补发延迟消息
//     *
//     * @param starDelayTime 查找区间,开始的delayTime
//     * @param endDelayTime 查找区间,结束的delayTime
//     */
////    public void mqSendJob(Date starDelayTime, Date endDelayTime) {
////        List<AwardMqSendLogDO> sendLogList = awardMqSendLogDao.listAwardMqSendLogs(MqSendStatusEnum.TO_SEND.getIndex(),
////                Boolean.TRUE, starDelayTime, endDelayTime);
////        if (!CollectionUtils.isEmpty(sendLogList)) {
////            for (AwardMqSendLogDO awardMqSendLog : sendLogList) {
////                try {
////                    Message dto = buildMsg(Base64.getDecoder().decode(awardMqSendLog.getSendMsg()));
////                    Date delayDate = awardMqSendLog.getDelayTime();
////                    long delayTime = Math.max(delayDate.getTime() - System.currentTimeMillis(), 1L);
////                    dto.getMessageProperties().getHeaders().put("x-delay", delayTime);
////                    dto.getMessageProperties().getHeaders().put(AWARD_MQ_HEADER, awardMqSendLog.getId());
////                    rabbitTemplate.send(awardMqSendLog.getExchangeName(), awardMqSendLog.getRoutingKey(), dto);
////                    Integer updateCount = awardMqSendLogDao.updateStatusById(awardMqSendLog.getId(), MqSendStatusEnum.SEND_SUCCESS.getIndex());
////                    if (updateCount != Constants.ONE) {
////                        log.error("[award] mqSendJob 修改消息状态失败 id:{}", awardMqSendLog.getId());
////                    }
////                    if (log.isInfoEnabled()) {
////                        log.info("[award] 发送延迟mq消息成功{}", awardMqSendLog);
////                    }
////                } catch (Exception e) {
////                    log.error("[award] 发送延迟mq消息失败", e);
////                    Integer updateCount = awardMqSendLogDao.updateStatusById(awardMqSendLog.getId(), MqSendStatusEnum.SEND_FAIL.getIndex());
////                    if (updateCount != Constants.ONE) {
////                        log.error("[award] mqSendJob 修改消息状态失败 id:{}", awardMqSendLog.getId());
////                    }
////                }
////            }
////        } else {
////            if (log.isInfoEnabled()) {
////                log.info("[award] 没有待发送的消息");
////            }
////        }
////    }
//
//
//    /**
//     * 构造mq消息体
//     *
//     * @param topic
//     * @param map
//     * @return
//     */
////    private Message buildMsgWithMap(String topic, Map map) throws JsonProcessingException {
////        MessageProperties messageProperties = new MessageProperties();
////        // MQ头
////        messageProperties.setCorrelationId(UUID.randomUUID().toString());
////        messageProperties.setContentType("application/x-msgpack");
////        messageProperties.setContentEncoding("binary");
////        messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
////
////        // 自有头 必须
////        messageProperties.setHeader("lang", "py");
////        messageProperties.setHeader("task", "tasks.instances.mq.mq_handle");
////        messageProperties.setHeader("id", UUID.randomUUID().toString());
////        messageProperties.setHeader("root_id", UUID.randomUUID().toString());
////        messageProperties.setHeader("parent_id", UUID.randomUUID().toString());
////        messageProperties.setHeader("group", UUID.randomUUID().toString());
////
////        byte[] bytes = MsgPackFormatUtil.mqEncode(topic, map);
////        return new Message(bytes, messageProperties);
////    }
////
////
////    /**
////     * 构造mq消息体
////     *
////     * @param topic
////     * @param msg
////     * @return
////     */
////    private Message buildMsg(String topic, Object msg) throws JsonProcessingException {
////        MessageProperties messageProperties = new MessageProperties();
////        // MQ头
////        messageProperties.setCorrelationId(UUID.randomUUID().toString());
////        messageProperties.setContentType("application/x-msgpack");
////        messageProperties.setContentEncoding("binary");
////        messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
////
////        // 自有头 必须
////        messageProperties.setHeader("lang", "py");
////        messageProperties.setHeader("task", "tasks.instances.mq.mq_handle");
////        messageProperties.setHeader("id", UUID.randomUUID().toString());
////        messageProperties.setHeader("root_id", UUID.randomUUID().toString());
////        messageProperties.setHeader("parent_id", UUID.randomUUID().toString());
////        messageProperties.setHeader("group", UUID.randomUUID().toString());
////
////        byte[] bytes = MsgPackFormatUtil.mqEncode(topic, msg);
////        return new Message(bytes, messageProperties);
////    }
//
//    /**
//     * 构造mq消息体
//     *
//     * @param btyes
//     * @return
//     */
//    private Message buildMsg(byte[] btyes) throws JsonProcessingException {
//        MessageProperties messageProperties = new MessageProperties();
//        // MQ头
//        messageProperties.setCorrelationId(UUID.randomUUID().toString());
//        messageProperties.setContentType("application/x-msgpack");
//        messageProperties.setContentEncoding("binary");
//        messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
//
//        // 自有头 必须
//        messageProperties.setHeader("lang", "py");
//        messageProperties.setHeader("task", "tasks.instances.mq.mq_handle");
//        messageProperties.setHeader("id", UUID.randomUUID().toString());
//        messageProperties.setHeader("root_id", UUID.randomUUID().toString());
//        messageProperties.setHeader("parent_id", UUID.randomUUID().toString());
//        messageProperties.setHeader("group", UUID.randomUUID().toString());
//
//        return new Message(btyes, messageProperties);
//    }
//
////    /**
////     * 获取key，类名首字母小写
////     *
////     * @param o
////     * @return
////     */
////    private String getSimpleName(Object o) {
////        if (o == null) {
////            return "nothing";
////        }
////        char[] chars = o.getClass().getSimpleName().toCharArray();
////        if (Character.isUpperCase(chars[0])) {
////            chars[0] = Character.toLowerCase(chars[0]);
////        }
////        return new String(chars);
////    }
//}
